package nl.rainbowsheep.reisorg.rest.service.controller;

import nl.rainbowsheep.reisorg.rest.service.controller.exception.UsernameExistsException;
import nl.rainbowsheep.reisorg.rest.service.model.BurritoUser;
import nl.rainbowsheep.reisorg.rest.service.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * Controller for users
 */
@RestController
@RequestMapping("/user")
public class UserController {

    /**
     * use slf4j logger during debugging
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);

    @Autowired
    UserService userService;
        
    @RequestMapping(value = "/pages", method = RequestMethod.GET)
    @ResponseBody
    public Page<BurritoUser> getUsers(@RequestParam(value = "pageIndex", required = false, defaultValue = "0") Integer pageIndex, @RequestParam(value = "size", required = false, defaultValue = "20") Integer size) {
        Pageable pageable = new PageRequest(pageIndex, size, new Sort("id"));
        Page<BurritoUser> pageResult = userService.findAll(pageable);
        return pageResult;
    }

    @RequestMapping(value = "/getUserByName", method = RequestMethod.GET)
    @ResponseBody
    public BurritoUser getUserByName(@RequestParam(value = "name", required = true) String username) {
        BurritoUser burritoUser = userService.findByUsername(username);
        return burritoUser;
    }
    
    @RequestMapping(value = "/getUserById", method = RequestMethod.GET)
    @ResponseBody
    public BurritoUser getUserById(@RequestParam(value = "id", required = true) long id) {
        BurritoUser burritoUser = userService.findByBurritoUserId(id);
        LOGGER.debug("RESTSERVICE + " + burritoUser.getUsername());
        return burritoUser;
    }

    
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public @ResponseBody
    BurritoUser saveUser(@RequestBody BurritoUser user) throws Exception {
        if (userService.findByUsername(user.getUsername()) != null) {
            throw new UsernameExistsException(user.getUsername());
        }
        return userService.save(user);
    } 
}
